<script setup>
import AvatarUpload from "@/components/AvatarUpload.vue";
import {onBeforeMount, reactive, ref} from "vue";
import {useRouter} from "vue-router";
import {getAvatar, getRequest, postRequest} from "@/util/api";
import {flushLocalStorage, generateDownloadUuid, message} from "@/util/util";

const username = localStorage.getItem("username");
const router = useRouter();

function logout() {
  getRequest("/user/logout", null, () => {
    flushLocalStorage();
    router.push({
      path: '/login'
    });
  });
}

const data = reactive({
  dialog: false,
  imgSrc: ""
});

onBeforeMount(async () => {
  data.imgSrc = await getAvatar();
});

const avatarUploadRef = ref();

function uploadAvatar() {
  avatarUploadRef.value.getCanvasFile((formData) => {
    generateDownloadUuid((uuid) => {
      postRequest("/user/uploadAvatar", {
        uuid
      }, formData, async (res) => {
        message(res.data.msg, "success");
        localStorage.setItem("avatarUrl", res.data.data);
        data.imgSrc = await getAvatar();
      });
    });
  });
}
</script>

<template>
  <div class="container">
    <img :src="data.imgSrc" alt=""/>

    <el-form>
      <el-form-item label="用户名">
        <el-input v-model="username" readonly/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="data.dialog = true">更换头像</el-button>
        <el-button type="danger" @click="logout">退出登录</el-button>
      </el-form-item>
    </el-form>
  </div>

  <el-dialog v-model="data.dialog" style="width: fit-content" title="更换头像">
    <AvatarUpload ref="avatarUploadRef"/>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.dialog = false">取消</el-button>
        <el-button type="primary" @click="uploadAvatar">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.container {
  padding: 30px;

  img {
    width: 200px;
    height: 200px;
    border-radius: 50%;
    margin-bottom: 30px;
  }
}
</style>